'use client'

import { Card, Tag, Button, Image } from 'antd'
import { GlobalOutlined, DownloadOutlined, EyeOutlined } from '@ant-design/icons'
import Link from 'next/link'
import { formatDateShort } from '../utils/dateUtils'
import { downloadFile, generateDownloadFilename } from '../utils/downloadUtils'

const { Meta } = Card

export default function ProductCard({ product }) {
    const {
        id,
        title,
        description,
        type,
        url,
        thumbnail_url,
        created_at
    } = product

    // 产品类型配置
    const typeConfig = {
        website: {
            label: '网站',
            color: 'blue',
            icon: <GlobalOutlined />,
            actionText: '访问网站',
            actionIcon: <GlobalOutlined />
        },
        app: {
            label: '应用',
            color: 'green',
            icon: <DownloadOutlined />,
            actionText: '下载应用',
            actionIcon: <DownloadOutlined />
        }
    }

    const config = typeConfig[type] || typeConfig.website

    // 处理缩略图
    const thumbnailSrc = thumbnail_url || '/placeholder-image.svg'

    // 处理描述文本截断
    const truncatedDescription = description && description.length > 100
        ? description.substring(0, 100) + '...'
        : description

    // 处理外部链接点击和文件下载
    const handleActionClick = (e) => {
        e.preventDefault()

        if (type === 'website' && url) {
            window.open(url, '_blank', 'noopener,noreferrer')
        } else if (type === 'app' && url) {
            // 应用类型：触发文件下载
            let downloadUrl = url

            // 如果是本地文件路径，使用下载 API
            if (url.startsWith('/uploads/')) {
                downloadUrl = `/api/download${url}`
            }

            const filename = generateDownloadFilename(title, url)

            downloadFile(downloadUrl, filename, {
                onSuccess: () => {
                    console.log(`${title} 下载成功`)
                },
                onError: (error) => {
                    console.error('下载失败:', error)
                }
            }).catch(error => {
                console.error('下载错误:', error)
            })
        }
    }

    return (
        <Card
            hoverable
            className="h-full flex flex-col shadow-sm hover:shadow-md transition-shadow duration-200"
            cover={
                <div className="relative h-48 overflow-hidden">
                    <Image
                        alt={title}
                        src={thumbnailSrc}
                        fallback="/placeholder-image.svg"
                        className="w-full h-full object-cover"
                        preview={false}
                    />
                    {/* 产品类型标签 */}
                    <div className="absolute top-2 right-2">
                        <Tag color={config.color} icon={config.icon}>
                            {config.label}
                        </Tag>
                    </div>
                </div>
            }
            actions={[
                <Link key="view" href={`/product/${id}`}>
                    <Button type="text" icon={<EyeOutlined />} size="small">
                        查看详情
                    </Button>
                </Link>,
                <Button
                    key="action"
                    type="text"
                    icon={config.actionIcon}
                    size="small"
                    onClick={handleActionClick}
                    disabled={!url}
                >
                    {config.actionText}
                </Button>
            ]}
        >
            <Meta
                title={
                    <div className="flex items-center justify-between">
                        <span className="truncate flex-1" title={title}>
                            {title}
                        </span>
                    </div>
                }
                description={
                    <div className="space-y-2">
                        <p className="text-gray-600 text-sm leading-relaxed">
                            {truncatedDescription || '暂无描述'}
                        </p>
                        {created_at && (
                            <p className="text-xs text-gray-400">
                                创建时间: {formatDateShort(created_at)}
                            </p>
                        )}
                    </div>
                }
            />
        </Card>
    )
}